package rsj.db;


import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

import static common.util.prop.PropUtils.getIs;

@Component
public class PostgresqlConn {
    private static Properties properties = new Properties();
    private static final Logger logger = LoggerFactory.getLogger(PostgresqlConn.class);

    private static DataSource dataSource;

    private static String url;

    /**
     * 数据库url
     * @param url url
     */
    @Value("${spring.datasource.url}")
    public void setUrl(String url) {
        PostgresqlConn.url = url;
    }

    @Autowired
    public void setDataSource(DataSource dataSource) {
        PostgresqlConn.dataSource = dataSource;
    }




    //
    //private static String url = "";
    //
    //static {
    //    //PostgresqlConn p = new PostgresqlConn();
    //    //loadFile("rsjdb.properties");
    //}


    public static Properties loadFile(String propFileName) {

        InputStream in;
        try {
            in = getIs(propFileName);
            properties.load(in);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        logger.error("{}::properties:::{}", propFileName, JSON.toJSONString(properties));
        return properties;
    }

    //public static Connection getConnection() {
    //    Connection connection = null;
    //    url=properties.getProperty("url");
    //    try{
    //        Class.forName(Driver.class.getName());
    //        connection = DriverManager.getConnection(url,properties);
    //        connection.setAutoCommit(true);
    //    }catch (Exception e) {
    //    	e.printStackTrace();
    //    	throw new RuntimeException("pg数据库连接失败！");
    //    }
    //    return connection;
    //}


    public static Connection getConnection() {
        Connection connection;
        try {
            connection = DataSourceUtils.getConnection(dataSource);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("pg数据库连接失败！");
        }
        return connection;
    }


    public static Connection getConnectionMonitor() {
        //Connection connection = null;
        //url = properties.getProperty("url");
        //try {
        //    Class.forName(Driver.class.getName());
        //    connection = DriverManager.getConnection(url, properties);
        //    connection.setAutoCommit(true);
        //} catch (Exception e) {
        //    // e.printStackTrace();
        //}
        return getConnection();
    }

    public static String getConnectionUriMonitor() {
        return url;
    }



}
